package de.upb.messerschmidt.set;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import de.upb.messerschmidt.set.entity.Person;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * This Servlet can return all users or specific ones ({@link Person}).
 * 
 * @author Tim Messerschmidt
 * 
 */
public class GetPersonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String prename = req.getParameter("prename");
		String name = req.getParameter("name");

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery(Person.class);
		query.setOrdering("name desc");

		// All the profiles or only one?
		if (prename == null && name == null) {
			try {
				List<Person> results = (List<Person>) query.execute();

				if (!results.isEmpty()) {
					Gson gson = new Gson();
					String json = gson.toJson(results);
					resp.setStatus(200);
					resp.getWriter().println(URLEncoder.encode(json, "UTF-8"));
				} else {
					resp.setStatus(200);
					resp.getWriter().println("no persons yet");
				}
			} finally {
				query.closeAll();
			}
		} else if (!(prename.equals("") && name.equals(""))) {
			query.setFilter("prename == prenameString && name == nameString");
			query.declareParameters("String prenameString, String nameString");

			try {
				List<Person> results = (List<Person>) query.execute(prename,
						name);

				if (!results.isEmpty()) {
					Gson gson = new Gson();
					String json = gson.toJson(results);
					resp.setStatus(200);
					resp.getWriter().println(URLEncoder.encode(json, "UTF-8"));
				} else {
					resp.setStatus(200);
					resp.getWriter().println("no persons yet");
				}
			} finally {
				query.closeAll();
			}
		}
	}
}
